#include "login.h"
#include "ui_login.h"

login::login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);
//数据库连接准备
    if(QSqlDatabase::contains("connection")){
        login_db = QSqlDatabase::database("connection");
    }else{
        login_db = QSqlDatabase::addDatabase("QMYSQL","connection");
    }
    login_db.setHostName("127.0.0.1");
    login_db.setPort(3306);
    login_db.setDatabaseName("experimentdb");
    login_db.setUserName("root");
    login_db.setPassword("1234");
    if(login_db.open()){
        qDebug("login_SQL connect success!");
    }else{
        qDebug("login_SQL connect failed!");
    }
}

login::~login()
{
    delete ui;
}
//用户注册
void login::on_login_ok_clicked()
{
    loginName = ui->login_name->text();
    logingID = ui->login_id->text();
    loginPsd = ui->login_password->text();
    loginPsd_2 = ui->login_psd_again->text();
//工号查重准备，避免相同工号出现
    cmd = QString("select * from account where account_id ='%1'").arg(logingID);
    QSqlQuery query(cmd,login_db);
    while(query.next()){
        id_db =query.value(1).toString();
    }
//教师注册
    if(ui->login_teacher->isChecked()){
        loginIdentity ="教师";
        if(loginPsd != loginPsd_2){
            QMessageBox::critical(this,"注册警告","两次密码输入不一致！");
        }else if(id_db == logingID){
            QMessageBox::critical(this,"注册警告","该工号已经注册过！");
        }else{
        cmd = QString("insert into account(account_name,account_id,account_password,account_identity) values('%1', '%2', '%3','%4')").arg(loginName).arg(logingID).arg(loginPsd).arg(loginIdentity);
        QSqlQuery query(cmd,login_db);
        QMessageBox::information(this,"注册提示","注册成功！");
        ui->login_name->clear();
        ui->login_id->clear();
        ui->login_password->clear();
        ui->login_psd_again->clear();
        }
    }else{//学生注册
        loginIdentity ="学生";
        if(loginPsd != loginPsd_2){
            QMessageBox::critical(this,"注册警告","两次密码输入不一致！");
        }else if(id_db == logingID){
            QMessageBox::critical(this,"注册警告","该工号已经注册过！");
        }else{
        cmd = QString("insert into account(account_name,account_id,account_password,account_identity) values('%1', '%2', '%3','%4')").arg(loginName).arg(logingID).arg(loginPsd).arg(loginIdentity);
        QSqlQuery query(cmd,login_db);
        QMessageBox::information(this,"注册提示","注册成功！");
        ui->login_name->clear();
        ui->login_id->clear();
        ui->login_password->clear();
        ui->login_psd_again->clear();
        }
    }
}
